class TreeNode:
    def __init__(self, val=0, left=None, right=None):
        self.val = val
        self.left = left
        self.right = right


def levelOrder(root):
    res = []
    if not root:
        return res
    dfs(root, res, 0)
    return res


def dfs(node, res, level):
    if not node:
        return
    # 初始化层级的结果数组
    if level > len(res) - 1:
        res.append([])
    res[level].append(node.val)
    if node.left:
        dfs(node.left, res, level + 1)
    if node.right:
        dfs(node.right, res, level + 1)


root = TreeNode(10)
root.left = TreeNode(5)
root.right = TreeNode(15)
root.left.left = TreeNode(3)
root.left.right = TreeNode(7)
root.right.right = TreeNode(18)
print(levelOrder(root))
